package com.cw.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cw.data.ConstantEnum;
import com.cw.data.Result;
import com.cw.myexception.MyException;
import com.cw.pojo.TbSeller;
import com.cw.service.SellerService;
import com.cw.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("sellerController")
public class SellerController {

    @Reference
    private SellerService sellerService;

    @RequestMapping("checkName")
    @ResponseBody
    public Result checkName(String sellerId) {

        try {

            Boolean b = sellerService.checkName(sellerId);

            return Result.result(ConstantEnum.SUCCESS).setData(b);
        }catch (Exception e) {

            e.printStackTrace();

            return Result.result(ConstantEnum.ERROR);
        }
    }

    @RequestMapping("toRegister")
    @ResponseBody
    public Result toRegister(TbSeller tbs) {

        try {

            String password = tbs.getPassword();

            tbs.setSalt(ShiroUtils.generateSalt(6));

            tbs.setPassword(ShiroUtils.encryptPassword("MD5", password, tbs.getSalt(), 10));

            sellerService.toRegister(tbs);

            return Result.result(ConstantEnum.SUCCESS).setData(true);
        }catch (Exception e) {

            e.printStackTrace();

            return Result.result(ConstantEnum.ERROR).setData(false);
        }
    }

    @RequestMapping("login")
    @ResponseBody
    public Result login(String sellerId, String password) {

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(sellerId, password);

        try {

            subject.login(token);

        }catch (UnknownAccountException e1) {

            return Result.result(ConstantEnum.ERROR).setData("用户不存在");

        }catch (IncorrectCredentialsException e2) {

            return Result.result(ConstantEnum.ERROR).setData("密码错误");
        }catch (MyException e3) {

            return Result.result(ConstantEnum.ERROR).setData(e3.getMessage());
        }

        return Result.result(ConstantEnum.SUCCESS).setData("登录成功");

    }
}
